#include "nextmaploder.h"
#include "apple.h"
#include "qgraphicsitem.h"
#include<gamedefine.h>
#include<player.h>
#include<trapground.h>
#include<enemy.h>
#include<hurtground.h>
Player*nextnewplayer=nullptr;
void nextmaploder::applerestart()
{
    int number=applepoint->size();
    for(int i=0;i<number;i++){
        bool is_damage=false;
        for( QPointF& appleone : *damageappleonint){
            if(appleone==applepoint->at(i)){
                is_damage=true;
                appleone.setX(0);
                appleone.setY(0);
            }

        }
        if(is_damage){

            apple*appletemp=new apple(applepoint->at(i).x(),applepoint->at(i).y());
            m_scene->addItem(appletemp);

        }

    }
}

nextmaploder::nextmaploder(QGraphicsScene* scene)
{
    damageappleonint=new QVector<QPointF>;
    applepoint=new QVector<QPointF>;
    m_scene=scene;
}

void nextmaploder::loadLevel(const QString &filePath)
{

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开地图文件:" << filePath;
        return;
    }
    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    QJsonObject temp1=doc.object();
    QJsonValue layertemp2=temp1["layers"];
    QJsonArray layers = layertemp2.toArray();//避免链式调用，提取根对象中的层
    QJsonValue tilesetstemp2=temp1["tilesets"];
    QJsonArray tilesets=tilesetstemp2.toArray();//提取根对象中的图集
    if (tilesets.isEmpty()) {
        qWarning() << "No tileset found!";
        return;
    }

    QJsonObject tileset = tilesets[0].toObject();
    firstGid = tileset["firstgid"].toInt();
    tileWidth = tileset["tilewidth"].toInt();
    tileHeight = tileset["tileheight"].toInt();
    margin = tileset["margin"].toInt();
    spacing = tileset["spacing"].toInt();
    columns = tileset["columns"].toInt();
    QString imagePath = ":/gameresource/Terrain (16x16).png";
    QString imagePath2 = ":/gameresource/Blue.png";//要注意这里的路径还没有进行处理！！！！！！路径已经处理过了，目前我直接使用绝对路径可能后期会出现适配的问题要注意。
    if (!tilesetImage.load(imagePath)||!tilesetImage2.load(imagePath2)) {
        qWarning() << "Failed to load tileset image:" << imagePath;
    }
    for (const QJsonValue& layerValue : std::as_const(layers)) {
        QJsonObject layerObj = layerValue.toObject();
        QString layerType = layerObj["type"].toString();

        if (layerType == "tilelayer") {
            parseTileLayer(layerObj);
        } else if (layerType == "objectgroup") {
            parseObjectLayer(layerObj);
        }


    }//遍历所有层进行处理
}
void nextmaploder::parseTileLayer(const QJsonObject& layer) {
    QString layerName = layer["name"].toString();
    int layerwidth = layer["width"].toInt();
    int layerheight = layer["height"].toInt();
    QJsonArray data = layer["data"].toArray();//提取该图块层的瓷砖个数（宽多少个，长多少个），但是事实上每个图块层包括了整个地图的所有图块，所有其实也是地图大小

    // 获取图块属性（示例：检查是否可碰撞）
    bool isCollidable = (layerName == "terrain");

    // 遍历所有图块
    for (int y = 0; y < layerheight; ++y) {
        for (int x = 0; x < layerwidth; ++x) {
            int tileId = data[y * layerwidth + x].toInt();
            if(tileId==0)continue;// 空图块跳过

            Specialteam* tile = new Specialteam();//记住自己改了一下
            // 从图集加载纹理
            tile->setPos(x * 16, y * 16);//单个图块为32x32的大小，目前先这样加载，设置图块的实际像素位置

            if (isCollidable) {
                tile->setPixmap(getTileTexture(tileId));
                // 添加碰撞盒（比图块略小防止卡墙）
                //tile->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
                tile->setData(iscollision, true);//标记第一个属性是否可collidable是true；
                tile->setData(ObjectType,1);//one是可碰撞地形
                m_scene->addItem(tile);
            }
            else{

                tile->setData(iscollision,false);
                tile->setData(ObjectType,2);//two是不可碰撞地形

            }


        }
    }
}
void nextmaploder::parseObjectLayer(const QJsonObject &layer)//处理对对象层的加载
{
    QJsonArray objects = layer["objects"].toArray();//提取对象层中的每一个对象
    for (const QJsonValue& objValue : std::as_const(objects)) {
        QJsonObject obj = objValue.toObject();
        QString type = obj["type"].toString();
        qreal x = obj["x"].toDouble();
        qreal y = obj["y"].toDouble();
        if(type=="spawn_point"){
            nextnewplayer=new Player(x,y,this);

            //  int tiled=obj["gid"].toInt();
            //记住自己改了一下
            //  newplayer->setPixmap(getTileTexture(tiled));
            m_scene->addItem(nextnewplayer);
            nextnewplayer->heart=new hearts(16,16,m_scene);
            nextnewplayer->heart2=new hearts(32,16,m_scene);


        }
        if(type=="trapground"){
            trapground* trapgroundone=new trapground(x,y);
            m_scene->addItem(trapgroundone);

        }
        else if(type=="enemy"){
            //int tiled=obj["gid"].toInt();
           // bool flipHorizontal = (tiled & 0x80000000) != 0;
            enemy*enemyone=new enemy(x,y,true,m_scene);

            //处理敌人生成，和敌人方向的问题
            enemyone->setPixmap(QPixmap(":/gameresource/20 Enemies(1)_resized (1).png"));
            // m_scene->addItem(enemyone);
        }
        else if(type=="hurtground"){
            hurtground*hurtgroundone=new hurtground(x,y);
            m_scene->addItem(hurtgroundone);
        }
        else if(type=="hurtgroundup"){

            hurtground*hurtgroundone=new hurtground(x,y);
            hurtgroundone->setPixmap(hurtgroundone->flipVertical());
            m_scene->addItem(hurtgroundone);
        }
        else if(type=="apple"){

            apple* appleone=new  apple(x,y);

            m_scene->addItem(appleone);
            // appleitems->append(appleone);
            applepoint->append(QPointF(x,y));

        }


    }
}

QPixmap nextmaploder::getTileTexture(int gid){
    // 去除翻转/旋转标志位
    bool flipHorizontal = (gid & 0x80000000) != 0;
    bool flipVertical = (gid & 0x40000000) != 0;
    bool flipDiagonal = (gid & 0x20000000) != 0;
    int actualGid = gid & ~(0x80000000 | 0x40000000 | 0x20000000);

    // 计算局部 ID
    int localId = actualGid - firstGid;

    // 计算行列索引
    int row = localId / columns;
    int col = localId % columns;

    // 计算图块在图集中的坐标
    int x = margin + col * (tileWidth + spacing);
    int y = margin + row * (tileHeight + spacing);

    // 提取子图块
    if(gid<243){
        QPixmap tileTexture = tilesetImage.copy(x, y, tileWidth, tileHeight);
        if (flipHorizontal) tileTexture = tileTexture.transformed(QTransform().scale(-1, 1));
        if (flipVertical) tileTexture = tileTexture.transformed(QTransform().scale(1, -1));
        if (flipDiagonal) tileTexture = tileTexture.transformed(QTransform().rotate(90));
        return tileTexture;
    }
    else{
        QPixmap tileTexture=tilesetImage2.copy(x,y,tileWidth,tileHeight);
        if (flipHorizontal) tileTexture = tileTexture.transformed(QTransform().scale(-1, 1));
        if (flipVertical) tileTexture = tileTexture.transformed(QTransform().scale(1, -1));
        if (flipDiagonal) tileTexture = tileTexture.transformed(QTransform().rotate(90));
        return tileTexture;
    }
    // 处理翻转/旋转



}//通过这个加载图集中的纹理
